<?php

// +----------------------------------------------------------------------
// | yogurt
// +----------------------------------------------------------------------
// +----------------------------------------------------------------------
// | Author: fengyi <1719847255.qq.com>
// +----------------------------------------------------------------------

namespace yogurt;

use yogurt\file\File;

class Request
{

    private static $_instance;

    /**
     * 追加数据
     * @param $data
     * @return array|mixed
     */
    public static function pushData($data)
    {
        $input = file_get_contents('php://input');
        if (!empty($input)) {
            $data = array_merge($data, json_decode($input, true));
        }
        return $data;
    }

    /**
     * 获取get请求参数
     * @param string $key
     * @return mixed|string
     */
    public static function get($key = '')
    {
        $s = basename($_SERVER['REQUEST_URI']);
        if ((strpos($s, '?s=') === false) && (strpos($s, '&s=') === false)) {
            if (isset($_GET['s'])) {
                unset($_GET['s']);
            }
        }
        if (isset($_SERVER['SCRIPT_URL'])) {
            $url = str_replace('.', '_', $_SERVER['SCRIPT_URL']);
            if (isset($_GET[$url])) {
                unset($_GET[$url]);
            }
        }
        $_GET = self::pushData($_GET);
        return $key == '' ? self::filter($_GET) : self::filter($_GET[$key] ?? '');
    }

    /**
     * 获取post请求参数
     * @param string $key
     * @return mixed|string
     */
    public static function post($key = '')
    {
        $_POST = self::pushData($_POST);
        return $key == '' ? self::filter($_POST) : self::filter($_POST[$key] ?? '');
    }

    /**
     * 获取header头信息
     * @param string $key
     * @return array|false|mixed
     */
    public static function header($key = '')
    {
        $headers = getallheaders();
        return $key == '' ? $headers : $headers[$key] ?? false;
    }

    /**
     * 获取上传的文件
     * @param $key
     * @return object
     */
    public static function file($key)
    {
        return File::get($key);
    }

    public static function param($key = '')
    {
        $get = self::get($key);
        return empty($get) ? self::post($key) : $get;
    }

    /**
     * 当前请求的模块
     * @return mixed
     */
    public static function model()
    {
        return Builder::$module;
    }

    /**
     * 当前请求控制器
     * @return mixed
     */
    public static function controller()
    {
        return Builder::$controller;
    }

    /**
     * 当前请求方法
     * @return false|mixed|string
     */
    public static function action()
    {
        return Builder::$action;
    }

    /**
     * 过滤请求参数
     * @param $data
     * @return mixed|string
     */
    public static function filter($data)
    {
        if (is_array($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = htmlspecialchars(str_replace('//', '', trim($v)));
            }
        } else {
            $data = htmlspecialchars(str_replace('//', '', trim($data)));
        }
        return $data;
    }

    /**
     * 判断是否是GET请求
     * @return bool
     */
    public static function isGet()
    {
        return $_SERVER['REQUEST_METHOD'] == 'GET';
    }

    /**
     * 判断是否是POST请求
     * @return bool
     */
    public static function isPost()
    {
        return $_SERVER['REQUEST_METHOD'] == 'POST';
    }

    /**
     * 获取客户端IP地址
     * @return mixed|string
     */
    public static function ip()
    {
        $ip = false;
        //客户端IP 或 NONE
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        //多重代理服务器下的客户端真实IP地址（可能伪造）,如果没有使用代理，此字段为空
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = false;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!preg_match('/^(10│172.16│192.168)./', $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        //客户端IP 或 (最后一个)代理服务器 IP
        return $ip ?: $_SERVER['REMOTE_ADDR'];
    }

    /**
     * 获取访问URL
     * @param bool $full
     * @return mixed
     */
    public static function url($full = true)
    {
        $url = 'cli' == PHP_SAPI ? realpath($_SERVER['argv'][0]) : $_SERVER['REQUEST_URI'];
        if ($full) {
            $scheme = $_SERVER['REQUEST_SCHEME'];
            $host = $_SERVER['HTTP_HOST'];
            return $scheme . '://' . $host . $url;
        }
        return $url;
    }

    /**
     * 获取请求方式
     * @return mixed|string
     */
    public static function method()
    {
        return $_SERVER['REQUEST_METHOD'] ?? '';
    }

    public static function register()
    {
        if (!self::$_instance instanceof self) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }


}
